package com.example.demo.service.impl;

import com.example.demo.dao.CommodityRespository;
import com.example.demo.domain.Commodity;
import com.example.demo.service.CommodityService;
import com.google.common.collect.Lists;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommodityServiceImpl implements CommodityService {
    @Resource
    CommodityRespository commodityRespository;

    @Override
    public long count() {
        return commodityRespository.count();
    }

    @Override
    public Commodity save(Commodity commodity) {
        return commodityRespository.save(commodity);
    }

    @Override
    public void delete(Commodity commodity) {
            commodityRespository.delete(commodity);
    }

    @Override
    public Iterable<Commodity> getAll() {
        return commodityRespository.findAll();
    }

    @Override
    public List<Commodity> getByName(String name) {
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name",name);

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(matchQueryBuilder)
                .build();
        Iterable<Commodity>  iterable= commodityRespository.search(searchQuery);
        return Lists.newArrayList(iterable);

    }

    @Override
    public Page<Commodity> pageQuery(Integer pageNo, Integer pageSize, String kw) {
        Pageable pageable = PageRequest.of(pageNo,pageSize);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
                .withPageable(pageable)
                .build();
        return commodityRespository.search(searchQuery);
    }

    @Override
    public List<Commodity> divideWordsQuery(Pageable pageable, String kw) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name","kw");
        boolQueryBuilder.must(matchQuery);
        Iterable<Commodity> commodities = commodityRespository.search(matchQuery,pageable);
        return Lists.newArrayList(commodities);
    }
}
